package com.kth.subtranslator.driver;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.kth.subtranslator.IBatchTranslateCallBack;
import com.kth.subtranslator.ITranslateDriverConfiguration;
import com.kth.subtranslator.TranslateEngine.Language;

public class BabelFishDriver extends AbstractTranslateDriver {

	private final DefaultHttpClient httpclient; 
	
	public BabelFishDriver() {
		httpclient = new DefaultHttpClient();
	}
	
	@Override
	public String translate(String text, Language fromLang, Language toLang) {
		return null;
	}

	@Override
	public Collection<String> batchTranslate(Collection<String> text,
			Language fromLang, Language toLang, IBatchTranslateCallBack callBack) {
		List<String> results = new ArrayList<String>();
		int i = 0;
		for (String t : text) {
			if (isStopped()) {
				return results;
			}
			String translatedText = internalTranslate(t, getLanguageString(fromLang, toLang));
			callBack.onBatchTranslated( Arrays.asList(translatedText), i );
			results.add( translatedText );
			i++;
		}
		return results;
	}

	private String internalTranslate(String text, String languageMode) {
		if (text != null && !text.isEmpty()) {
			return doPost("http://babelfish.yahoo.com/translate_txt", text, languageMode);
		}
		else {
			return "";
		}
	}

	private String doPost(String urlStr, String text, String languageMode) {
		
		NTCredentials creds = new NTCredentials("axddd", "xxxx", "smllx137", "be");
//		httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
		httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("proxy.ict", 8080),
                creds);
//		HttpHost proxy = new HttpHost("proxy.ict", 8080);
//		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		
		httpclient.getParams().setParameter("http.useragent", "Subtitle Translator");
		HttpPost httpPost = new HttpPost(urlStr);
		
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("lp", languageMode));
		nameValuePairs.add(new BasicNameValuePair("trtext", text));
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		
	    ResponseHandler<String> responseHandler = new BasicResponseHandler();
	    
	    
        try {
        	System.out.println("sending request ...");
			String responseBody = httpclient.execute(httpPost, responseHandler);
			Document doc = Jsoup.parse(responseBody);
			Element elem = doc.getElementById("result");
			Element subElem = elem.child(0);
			if (subElem != null) {
				return subElem.text();
			}
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	    
		return "";
	}

	@Override
	public Collection<Language> getSupportedLanguage() {
		return Arrays.asList(Language.FRENCH, Language.ENGLISH);
	}

	@Override
	public String getName() {
		return "Babel Fish";
	}

	private String getLanguageString(final Language fromLang, final Language toLang) {
		StringBuilder sb = new StringBuilder();
		if (Language.ENGLISH.equals(fromLang)) {
			sb.append("en");
		}

		sb.append("_");

		if (Language.FRENCH.equals(toLang)) {
			sb.append("fr");
		}
		return sb.toString();
	}

	/* (non-Javadoc)
	 * @see com.kth.subtranslator.ITranslateDriver#getSupportedTargetLanguage(com.kth.subtranslator.TranslateEngine.Language)
	 */
	@Override
	public Collection<Language> getSupportedTargetLanguage(Language fromLang) {
		return getSupportedLanguage();
	}

	/* (non-Javadoc)
	 * @see com.kth.subtranslator.ITranslateDriver#getConfiguration()
	 */
	@Override
	public ITranslateDriverConfiguration getConfiguration() {
		return null;
	}

}
